﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemBase : MonoBehaviour, IEventListener
{
    public Renderer render;

    public bool IsActed; // 记录是否激活
    /// <summary>
    /// 接受消息
    /// </summary>
    /// <param name="id"></param>
    /// <param name="param1"></param>
    /// <param name="param2"></param>
    /// <returns></returns>
    public virtual bool HandleEvent(int id, object param1, object param2)
    {
        switch (id)
        {
            case EventDef.ItemTurn:
                ItemAct();
                break;
        }
        return false;
    }

    public int EventPriority() { return 0; }
    /// <summary>
    /// 主要用于注册
    /// </summary>
    public virtual void Start()
    {
        if (EventNodeCore.GetInstance())
        {
            EventNodeCore.GetInstance().AttachEventListener(EventDef.ItemTurn, this);
        }
    }
    /// <summary>
    /// 主要用于注销
    /// </summary>
    public virtual void OnDestroy()
    {
        if (EventNodeCore.GetInstance())
        {
            EventNodeCore.GetInstance().DetachEventListener(EventDef.ItemTurn, this);
        }
    }

    private void OnEnable()
    {
        Initiate();
    }
    private void OnDisable()
    {
        Uninitiate();
    }
    /// <summary>
    /// 初始化方法
    /// </summary>
    public virtual void Initiate()
    {
        IsActed = false;
        render = GetComponent<Renderer>();
    }
    /// <summary>
    /// ondisable
    /// </summary>
    public virtual void Uninitiate()
    {
        //MapData.Instance.Unregiste(gameObject);
    }

    private void ItemAct()
    {
        if (IsActed)
        {
            ItemAction();
        }
    }
    /// <summary>
    /// 道具激活的行为
    /// </summary>
    public virtual void ItemAction()
    {
        StartCoroutine(VanishAct());
    }

    /// <summary>
    /// 向上飞走，逐渐消失
    /// </summary>
    /// <returns></returns>
    public virtual IEnumerator VanishAct()
    {
        float time = 0;
        render.material.color = new Color(
        render.material.color.r,
        render.material.color.g,
        render.material.color.b,
        //需要改的就是这个属性：Alpha值
        render.material.color.a);

        while (time < 1)
        {
            time += Time.deltaTime;
            transform.position += transform.up * 0.02f;
            if (render.material.color.a <= 1)
            {
                render.material.color = new Color(
                render.material.color.r
                , render.material.color.g,
                render.material.color.b,

                //减小Alpha值
                render.material.color.a - time / 50);
            }
            yield return null;
        }
        Destroy(gameObject);
    }
}